package com.bitin.adorn.core.security.expression;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.expression.EvaluationContext;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;

import java.util.function.Supplier;

/**
 * @author Mr.Lu
 * @since 2024/12/24 17:15
 */
public class Auth2MethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler {

    @Override
    public EvaluationContext createEvaluationContext(Supplier<Authentication> authentication, MethodInvocation invocation) {
        MethodSecurityExpressionOperations root = this.createSecurityExpressionRoot(authentication, invocation);
        Auth2MethodSecurityEvaluationContext context = new Auth2MethodSecurityEvaluationContext(root, invocation, this.getParameterNameDiscoverer());
        context.setBeanResolver(this.getBeanResolver());
        return context;
    }

    public MethodSecurityExpressionOperations createSecurityExpressionRoot(Supplier<Authentication> authentication, MethodInvocation invocation) {
        Auth2MethodSecurityExpressionRoot root = new Auth2MethodSecurityExpressionRoot(authentication.get());
        root.setThis(invocation.getThis());
        root.setPermissionEvaluator(this.getPermissionEvaluator());
        root.setTrustResolver(this.getTrustResolver());
        root.setRoleHierarchy(this.getRoleHierarchy());
        root.setDefaultRolePrefix(this.getDefaultRolePrefix());
        return root;
    }
}
